'use strict';

const Service = require('egg').Service;
const { Op } = require("sequelize");

class UserPointRecordService extends Service {
    // 获取流水信息
    async getList(params) {
        const {model} = this.app
        const {page, num, userId } = params
        let sql = {}, whereSql = {}

        whereSql = {
            user_id: userId,
            status: 1 //默认有效
        }

        sql = {
            where: whereSql,
            limit: num*1, // 返回数据量
            offset: num*(page-1), // 数据偏移量
        }
        const { count, rows } = await model.UserPointRecord.findAndCountAll(sql);
        const pageAll = Math.ceil(count/num)

        return {
            page: page,
            pageAll: pageAll,
            data: rows
        }
    }

    // 添加记录
    async addRecord(params) {
        const {model} = this.app
        const {userId, target, targetId, type, changeNum, desc} = params
        let sql = {}, whereSql = {}
        sql = {
            user_id: userId,
            target,
            target_id: targetId,
            type: type, //默认减少
            change_num: changeNum,
            desc,
            create_time: (new Date).getTime()/1000,
            update_time: (new Date).getTime()/1000
        }

        let result = await model.User.findByPk(userId)
        let userPoint = result.point
        sql.before_point = userPoint
        if (type == 1) {
            sql.after_point = userPoint*1 + changeNum
        } else {
            sql.after_point = userPoint - changeNum
        }
        

        // 建立事务对象
        let transaction;
        try {
            transaction = await model.transaction();

            await model.UserPointRecord.create(sql, {transaction})

            whereSql = {
                id: userId
            }

            await model.User.update({
                point: sql.after_point
            }, {
                where: whereSql,
                transaction
            })
            
            if (target == 1) {
                // 书籍
                await model.Novel.update({
                    point: model.literal(`point+${changeNum}`)
                }, {
                    where: {
                        id: targetId
                    },
                    transaction
                })
            }

            // 提交事务
            await transaction.commit();

            return
        } catch (error) {
            console.log(error)
            // 事务回滚
            await transaction.rollback();
            throw error;
        }
    }
}

module.exports = UserPointRecordService;
